import json
from collections import OrderedDict

from django.core.paginator import Paginator
from django.http import JsonResponse
from django.shortcuts import render
from datetime import date
# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.contents.models import ContentCategory
from apps.goods.models import GoodsChannel, GoodsCategory, SKU, GoodsVisitCount
from utils.goods import get_categories, get_breadcrumb, get_goods_specs
from haystack.views import SearchView

from utils.viewmixin import LoginMixin


class Index(View):

    def get(self, request):
        categories = get_categories()

        contents = {}

        content_categories = ContentCategory.objects.all()

        for cat in content_categories:
            contents[cat.key] = cat.content_set.filter(status=True).order_by("sequence")

        context = {"categories": categories, "contents": contents}

        # 3返回
        return render(request, "index.html", context=context)


class ListView(View):

    def get(self, request, category_id):
        # 1接收参数校验
        page = request.GET.get("page")
        page_size = request.GET.get("page_size")
        ordering = request.GET.get("ordering")
        try:
            # 根据category_id查出分类的对象
            category = GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "分类查询失败"})

        # 2面包屑导航数据
        breadcrumb = get_breadcrumb(category)
        # 3分类商品的数据的查询 （排序分页）
        skus = SKU.objects.filter(category=category, is_launched=True).order_by(ordering)
        paginator = Paginator(skus, page_size)
        page_skus = paginator.page(page)
        # 4把商品的数据转为字典
        sku_list = []
        for sku in page_skus:
            sku_list.append({
                "id": sku.id,
                "name": sku.name,
                "price": sku.price,
                "default_image": sku.default_image.url
            })

        count = paginator.num_pages
        # 5返回js

        return JsonResponse({"code": 0, "errmsg": "ok", "breadcrumb": breadcrumb, "list": sku_list, "count": count})


class HotGoodsView(View):

    def get(self, request, category_id):
        skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by("-sales")[:2]

        hot_skus = []
        for sku in skus:
            hot_skus.append({
                "id": sku.id,
                "default_image": sku.default_image.url,
                "name": sku.name,
                "price": sku.price
            })

        return JsonResponse({"code": 0, "errmsg": "ok", "hot_skus": hot_skus})


class MySearchView(SearchView):
    def create_response(self):
        # 获取搜索结果
        context = self.get_context()
        data_list = []
        for sku in context['page'].object_list:
            data_list.append({
                'id': sku.object.id,
                'name': sku.object.name,
                'price': sku.object.price,
                'default_image_url': sku.object.default_image.url,
                'searchkey': context.get('query'),
                'page_size': context['page'].paginator.num_pages,
                'count': context['page'].paginator.count
            })
        # 拼接参数, 返回
        return JsonResponse(data_list, safe=False)

class DetailView(View):
    """商品详情页"""

    def get(self, request, sku_id):
        """提供商品详情页"""
        # 获取当前sku的信息
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return render(request, '404.html')

        # 查询商品频道分类
        categories = get_categories()
        # 查询面包屑导航
        breadcrumb = get_breadcrumb(sku.category)

        # 获取规格
        specs = get_goods_specs(sku)

        # 渲染页面
        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'specs': specs,
        }
        return render(request, 'detail.html', context)


class CategoryVisitCountView(View):
    def post(self, request, cat_id):
        # - 1接收分类id校验
        # 去数据库查询cat_id对应的分类是否存在GoodsCategory（自己完成）

        # - 2查看当天这个分类在数据库有没有记录
        today = date.today()
        try:
            goodsVisitCount = GoodsVisitCount.objects.get(category_id=cat_id, date=today)
        except:
            # - 3没有就创建新数据
            goodsVisitCount = GoodsVisitCount()

        try:
            # - 4有的话count + 1
            goodsVisitCount.count += 1
            goodsVisitCount.date = today
            goodsVisitCount.category_id = cat_id
            goodsVisitCount.save()
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "失败"})

        # - 5返回响应
        return JsonResponse({"code": 0, "errmsg": "ok"})


class UserBrowseHistory(LoginMixin, View):
    def post(self, request):
        # 取出登录的user对象
        user = request.user

        # 1 接收请求
        json_data = json.loads(request.body)
        # 2 获取参数 sku_id
        sku_id = json_data.get("sku_id")
        # 3 验证参数
        try:
            SKU.objects.get(id=sku_id)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "没有这个商品"})

        # 4 连接redis
        redis_conn = get_redis_connection('history')
        pl = redis_conn.pipeline()
        # 5 去重复
        # key             value
        # history_userId   [newsku_id, sku_id, sku_id, sku_id, sku_id, sku_id]
        pl.lrem("history_%s" % user.id, 0, sku_id)

        # 6 保存 到reids
        pl.lpush("history_%s" % user.id, sku_id)

        # 7 保存5条   01234
        pl.ltrim("history_%s" % user.id, 0, 4)
        pl.execute()  # 执行管道

        # 8 返回json
        return JsonResponse({"code": 0, "errmsg": "ok"})

    def get(self, request):

        # - 获取用户id
        # 取出登录的user对象
        user = request.user
        # - 连接redis
        redis_conn = get_redis_connection('history')
        # - redis获取历史浏览记录的商品id
        sku_ids = redis_conn.lrange('history_%s' % user.id, 0, -1)

        # - 根据商品id获取商品sku对象 转为字典
        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            skus.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })
        # - 返回json数据
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'skus': skus})
